<template>
  <div :class="prefixCls">
    <Popover
      title=""
      trigger="click"
      v-model:visible="visible"
      :overlayClassName="`${prefixCls}__overlay`"
      v-if="getMsgEnabled"
    >
      <Badge :count="count" dot :numberStyle="numberStyle">
        <BellOutlined />
      </Badge>
      <template #content>
        <Tabs>
          <template v-for="item in listData" :key="item.key">
            <TabPane>
              <template #tab>
                {{ item.name }}
                <span v-if="item.count !== 0">({{ item.count }})</span>
              </template>
              <NoticeList :list="item.list" @title-click="onNoticeClick" />
              <a-button
                type="text"
                class="w-full mt-1"
                @click="onButtonClick(item)"
                v-if="item.btnHref"
              >
                {{ item.btnText }}
              </a-button>
            </TabPane>
          </template>
        </Tabs>
      </template>
    </Popover>
    <audio id="audioMessage" controls preload="auto" hidden muted>
      <source :src="audioMessageSrc" type="audio/mpeg" />
    </audio>
  </div>
</template>
<script lang="ts">
  import { computed, defineComponent, ref, onMounted, h } from 'vue';
  import { Popover, Tabs, Badge, Button, notification } from 'ant-design-vue';
  import { BellOutlined } from '@ant-design/icons-vue';
  import { tabListData, ListItem, TabItem } from './data';
  import NoticeList from './NoticeList.vue';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Msg, msgPullPoolMsg, msgUnreadMsg } from '/@/api/msg/msg';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useGo } from '/@/hooks/web/usePage';
  import { useFlashTitle } from '/@/hooks/web/useTitle';
  import { useEmitter } from '/@/store/modules/user';
  import { useUserStore } from '/@/store/modules/user';

  export default defineComponent({
    components: { Popover, BellOutlined, Tabs, TabPane: Tabs.TabPane, Badge, NoticeList },
    setup() {
      const { prefixCls } = useDesign('header-notify');
      const { createMessage } = useMessage();
      const visible = ref<boolean>(false);
      const listData = ref(tabListData);
      const { t } = useI18n();
      const go = useGo();
      const emitter = useEmitter();

      const publicPath = import.meta.env.VITE_PUBLIC_PATH || '/';
      const audioMessageSrc = publicPath + 'resource/msg/message.mp3';

      const flashTitle = useFlashTitle();

      const count = computed(() => {
        let count = 0;
        for (let i = 0; i < listData.value.length; i++) {
          const e = listData.value[i];
          count += e.count != undefined ? e.count : e.list.length;
        }
        return count;
      });

      const getMsgEnabled = computed(() => {
        const userStore = useUserStore();
        return userStore.getPageCacheByKey('msgEnabled', false);
      });

      onMounted(() => {
        if (getMsgEnabled.value) {
          unreadMsg(); // 先执行一次
          setInterval(unreadMsg, 180000); // 3分钟执行一次
          emitter.on('on-msg-notify-delete', (msg: Msg) => {
            listData.value[0].count = (listData.value[0].count || 1) - 1;
            listData.value[0].list.forEach((record) => {
              if (record.id == msg.id) {
                record.titleDelete = true;
              }
            });
          });
        }
      });

      function msgToListItem(msg: Msg): ListItem {
        const entity = msg.msgContentEntity || {};
        return {
          id: msg.id,
          avatar: 'ant-design:message-outlined',
          title: entity.title,
          description: entity.content,
          datetime: msg.sendDate,
          type: '1',
        };
      }

      async function unreadMsg() {
        let listCount = 0;
        const listItem: ListItem[] = [];
        const data = await msgUnreadMsg();
        if (!(data && data.result != 'login')) {
          return;
        }
        listCount = data.count || 0;
        const list = data.list || [];
        for (let i = 0; i < list.length; i++) {
          listItem.push(msgToListItem(list[i]));
        }
        listData.value = [
          {
            key: '1',
            name: t('sys.msg.title'),
            count: listCount,
            btnHref: '/msg/list',
            btnText: t('sys.msg.viewAllMsgButton'),
            list: listItem,
          },
        ];
        pullPoolMsg();
      }

      async function pullPoolMsg() {
        const data = await msgPullPoolMsg();
        if (!(data && data.result != 'login')) {
          return;
        }
        let list = (data || []) as any;
        const msgListData = listData.value[0];
        msgListData.count = msgListData.count + list.length;
        for (let i = 0; i < list.length; i++) {
          msgListData.list.push(msgToListItem(list[i]));
        }
        if (list.length != 0 && list.length > 5) {
          list = [
            {
              msgContentEntity: {
                title: t('sys.msg.mergeMsgTitle'),
                content: t('sys.msg.mergeMsgContent', [list.length]),
              },
              sendDate: '',
              sendUserName: '',
              id: '',
            },
          ];
        }
        for (let i = 0; i < list.length; i++) {
          const msg: Msg = list[0];
          const entity = msg.msgContentEntity || {};

          notification.open({
            message: entity.title,
            description: h('div', { innerHTML: entity.content }),
            placement: 'bottomRight',
            btn: () => {
              const btns: any = [];
              // TODO 根据业务需要，自行添加业务处理
              // if (isArray(entity.buttons)) {
              //   for (let btn of entity.buttons) {
              //     btns.push(
              //       h(
              //         Button,
              //         {
              //           type: 'primary',
              //           size: 'small',
              //           class: 'ml-2',
              //           onClick: () => {
              //             go(btn.herf);
              //             console.log(btn);
              //             notification.close(msg.id);
              //           },
              //         },
              //         { default: () => btn.name },
              //       ),
              //     );
              //   }
              // }
              btns.push(
                h(
                  Button,
                  {
                    type: 'primary',
                    size: 'small',
                    class: 'ml-2',
                    onClick: () => {
                      onNoticeClick({
                        id: msg.id,
                        avatar: 'ant-design:message-outlined',
                        title: entity.title,
                        description: entity.content,
                        datetime: msg.sendDate,
                        type: '1',
                      });
                      notification.close(msg.id);
                    },
                  },
                  { default: () => t('sys.msg.viewButton') },
                ),
              );
              return h('div', [btns]);
            },
            key: msg.id,
            duration: 60,
          });
          flashTitle();
        }
      }

      function onNoticeClick(record: ListItem) {
        visible.value = false;
        const index = (record.type as unknown as number) - 1;
        if (index == 0) {
          go('/msg/view?id=' + record.id);
        } else {
          createMessage.success('你点击了消息');
        }
        // setTimeout(() => {
        //   listData.value[index].count = (listData.value[index].count || 1) - 1;
        //   record.titleDelete = true;
        // }, 600);
      }

      function onButtonClick(tabItem: TabItem) {
        go(tabItem.btnHref);
        visible.value = false;
      }

      return {
        prefixCls,
        visible,
        listData,
        count,
        onNoticeClick,
        onButtonClick,
        numberStyle: {},
        audioMessageSrc,
        getMsgEnabled,
        t,
      };
    },
  });
</script>
<style lang="less">
  @prefix-cls: ~'jeesite-header-notify';

  .@{prefix-cls} {
    padding-top: 2px;

    &__overlay {
      max-width: 360px;

      .ant-popover-content {
        width: 300px;
      }
    }

    .ant-badge {
      font-size: 18px;

      .ant-badge-multiple-words {
        padding: 0 4px;
      }

      svg {
        width: 0.9em;
      }
    }
  }
</style>
